<?php

namespace app\admin\controller;

use app\common\AdminController;
use app\admin\model\Weblog as WeblogDB;
use app\admin\model\Operate as OperateDB;
class Index extends AdminController
{
    public  function getCount()
    {
        $weblogDB = new WeblogDB();
        $operateDB = new operateDB();
        $userCount = $weblogDB->whereNotNull('ipaddress')->group('ipaddress')->count();
        $webCount = $weblogDB->where('log_type', '=',1)->count();
        $logCount = $operateDB->where('log_type','=', 1)->count();
        return success('获取成功' ,[
            'userCount' => $userCount,
            'webCount' => $webCount,
            'logCount' => $logCount
        ]);
    }
    public function webdata()
    {
        $time = request()->post('time');
        $weblogDB = new WeblogDB();
        try {
            $list = $weblogDB
                ->whereBetweenTime('create_time', $time[0], $time[1])
                ->field('DATE_FORMAT(create_time,"%Y-%m-%d") as date,log_type,count(log_type) as count')
                ->group('log_type,date')
                ->select()
                ->toArray();
            $count = $weblogDB
                ->whereBetweenTime('create_time', $time[0], $time[1])
                ->field('log_type,count(log_type) as count')
                ->group('log_type')
                ->select()
                ->toArray();
            $type = $weblogDB->getTypeField();
            // 按 date 分组合并
            $grouped = array_reduce($list, function ($carry, $item) {
                $carry[$item['date']][$item['logType']] = $item['count'];
                return $carry;
            }, []);
            $res = [];
            foreach ($type as $key => $value) {
                foreach ($grouped as $date => $items) {
                    $res[$key][] = $items[$value] ?? 0;
                }
            }
            $time = array_keys($grouped);
            return success("获取成功", [
                'line' => [
                    'time' => $time,
                    'data' => $res
                ],
                'type' => $type,
                'count' => $count
            ]);
        } catch (\Throwable $th) {
            return error("获取失败");
        }
    }
}
